﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Iit.ITBI.MDSManager.Microsoft.MasterDataServices;


namespace Iit.ITBI.MDSManager
{
    class CustomDataTable : DataTable
    {

        public MDSQueryVersion QueryVersion
        {
            get;
            set;
        }

        public CustomDataTable(MDSQueryVersion QueryVersion)
        {
            this.QueryVersion = QueryVersion;
        }

        /// <summary>
        /// Convert the base datatable to an MDS operation result.
        /// </summary>
        /// <returns>OperationResult</returns>
        public OperationResult ToOperationResult()
        { 

            OperationResult operationResult = new OperationResult();
            Collection<Error> errors = new Collection<Error>();
            Error error;

            switch (this.QueryVersion)
            {                
                case MDSQueryVersion.DeletedMembersV1 :

                    foreach (DataRow dr in base.Rows)
                    {
                        //create a new error object
                        error = new Error();

                        //fill it with the relevant information
                        error.Code = (string)dr["ErrorCode"];
                        error.Description = string.Format("Failed to delete the member with the code {0}. Original error description: \"{1}\"", (string)dr["MemberCode"], (string)dr["ErrorText"]);
                        error.Context = new ErrorContext() { Type = ObjectType.MemberCode};

                        //add to the error collection
                        errors.Add(error);

                    }

                    //attach the error collection to the operation result
                    operationResult.Errors = errors.ToArray();

                    return operationResult;

                default :
                    throw new NotSupportedException (string.Format("The query version {0} is not supported  by the ToOperationResult method", QueryVersion.ToString()));

            }

            return null;
        
        
        }


    }
}
